# -*- coding: utf-8 -*-
# filename: handle.py
from fastapi import FastAPI, Request, Query, HTTPException, Response
from wechat_ import receive, reply
import hashlib
from source.aminer_main import AminerSearch

app = FastAPI()
# 请按照公众平台官网\基本配置中信息填写
TOKEN = 'zpy19970701'

async def await_aminer(rec_msg):
    to_user = rec_msg.FromUserName
    from_user = rec_msg.ToUserName
    input_text = rec_msg.Content
    aminer_search = AminerSearch()
    result = await aminer_search.run(input_text)
    result = f"{result}"
    reply_msg = reply.TextMsg(to_user, from_user, result)
    return reply_msg.send()

@app.get("/wx")
async def handle_get(
        signature: str = Query(None),
        timestamp: str = Query(None),
        nonce: str = Query(None),
        echostr: str = Query(None)
):
    try:
        if not signature or not timestamp or not nonce or not echostr:
            return "hello, this is handle view"

        # 将 token, timestamp, nonce 排序并拼接
        list_ = [TOKEN, timestamp, nonce]
        list_.sort()

        # 计算 SHA1 哈希值
        sha1 = hashlib.sha1()
        for item in list_:
            sha1.update(item.encode('utf-8'))
        hashcode = sha1.hexdigest()

        print("handle/GET func: hashcode, signature: ", hashcode, signature)

        # 验证签名
        if hashcode == signature:
            # 直接将 echostr 写入响应
            return Response(content=echostr, media_type="text/plain; charset=UTF-8")
        else:
            return Response(content="", media_type="text/plain; charset=UTF-8")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
@app.post("/wx")
async def handle_post(request: Request):
    try:
        web_data = await request.body()
        # 后台打日志
        rec_msg = receive.parse_xml(web_data.decode("utf-8"))
        if isinstance(rec_msg, receive.TextMsg) and rec_msg.MsgType == 'text':
            result = await await_aminer(rec_msg)
            return Response(content=result, media_type="text/xml")
    except Exception as e:
        return f'失败：{str(e)}'

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=80)